package com.wlyuan.open.scanner.utils.enums.named;

import com.wlyuan.core.marker.NamedValue;
import com.wlyuan.core.marker.NamedValueMap;
import com.wlyuan.core.named.CargoType;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public enum GoodsCategoryEnum implements NamedValue<Integer> {

    GENERAL(1, CargoType.NORMAL.getValue(), "普通货物"),
    DANGER(2, CargoType.DANGER.getValue(), "危险品"),
    TEMPERATURE_CONTROL(4, CargoType.TEMPERATURE.getValue(), "温控货物");

    private final Integer value;
    private final Integer newValue;
    private final String name;

    private static final Map<Integer, GoodsCategoryEnum> MAP = new NamedValueMap<>(GoodsCategoryEnum.class);

    public static GoodsCategoryEnum fromValue(Integer value) {
        return MAP.get(categoryTypes(value));
    }

    private static Integer categoryTypes(Integer value) {
        return Optional.ofNullable(value).map(v -> {
            if (v > 0) {
                return categoryType(categoryTypeList(v));
            }
            return v;
        }).orElse(null);
    }

    private static Integer categoryType(List<Integer> cargoTypes) {
        //如果勾选了危险物品，则以危险物品为主，其次以温控
        if (!CollectionUtils.isEmpty(cargoTypes)) {
            if (cargoTypes.contains(DANGER.value)) {
                return DANGER.value;
            }
            if (cargoTypes.contains(TEMPERATURE_CONTROL.value)) {
                return TEMPERATURE_CONTROL.value;
            }
        }
        return GENERAL.value;
    }

    private static List<Integer> categoryTypeList(Integer target) {
        List<Integer> keys = MAP.keySet().stream().collect(Collectors.toList());
        int n = keys.size();
        int nbit = 1 << n;
        int in;
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nbit; i++) {
            in = 0;
            list.clear();
            for (int j = 0; j < n; j++) {
                int tmp = 1 << j;
                if ((tmp & i) != 0) {
                    in += keys.get(j);
                    list.add(keys.get(j));
                }
            }
            if (in == target) {
                return list;
            }
        }
        return Collections.emptyList();
    }
}
